package popedom

import (
	"crypto/sha1"
	b64 "encoding/base64"
	"errors"
	"time"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/popedom/entity"

	"github.com/henrylee2cn/mahonia"
	"gorm.io/gorm"
)

func HashPassword(userNo, password string) string {
	h := sha1.New()
	enc := mahonia.NewEncoder("UTF-16LE")
	userAndPwd := enc.ConvertString(userNo + password)
	h.Write([]byte(userAndPwd))
	pwdH := b64.StdEncoding.EncodeToString(h.Sum(nil))
	return pwdH
}

//ModifyPassword 修改用户密码
func ModifyPassword(userID int, originalPassword string, newPassword string) error {
	user := entity.SysUser{}
	err := base.MYDB.Where(`"ID"=?`, userID).First(&user).Error
	if err != nil {
		return err
	}
	if len(newPassword) < 8 {
		return errors.New("新密码长度不能小于8位！")
	}
	oPwd := HashPassword(user.No, originalPassword)
	nPwd := HashPassword(user.No, newPassword)
	if oPwd != user.Password {
		return errors.New("原密码不等于旧密码！")
	}
	if nPwd == oPwd {
		return errors.New("新密码不能和旧密码一致！")
	}
	base.MYDB.Model(&user).Where(`"ID" = ?`, userID).Update("Password", nPwd)
	return nil
}

func GetPassword(userNo string) string {
	return HashPassword(userNo, "00000000")
}

//InintPassword 初始化密码
func InintPassword(userID int) error {
	user := entity.SysUser{}
	err := base.MYDB.Where(`"ID" = ?`, userID).First(&user).Error
	if err != nil {
		return err
	}
	nPwd := HashPassword(user.No, "00000000")
	base.MYDB.Model(&user).Where(`"ID" = ?`, userID).Update("Password", nPwd)
	return nil
}

//InintPassword 初始化密码
func InintPasswordByTx(tx *gorm.DB, userID int) error {
	user := entity.SysUser{}
	err := tx.Where(`"ID" = ?`, userID).First(&user).Error
	if err != nil {
		return err
	}
	nPwd := HashPassword(user.No, "00000000")
	tx.Model(&user).Where(`"ID" = ?`, userID).Update("Password", nPwd)
	return nil
}

//IsOverduePassword 密码是否过期
func IsOverduePassword(userID int) (bool, error) {
	user := entity.SysUser{}
	err := base.MYDB.Where(`"ID" = ?`, userID).First(&user).Error
	if err != nil {
		return false, err
	}
	after90 := user.ModifyPWDDate.AddDate(0, 0, 90)
	if user.ModifyPWDDate != nil && after90.Unix() > time.Now().Unix() {
		return true, nil
	}
	return false, nil
}
